<script lang="ts" setup>
import type { VxeTableGridOptions } from '@vben/plugins/vxe-table';

import type { SystemRoleApi } from '#/api/system/role';
import type { SystemUserApi } from '#/api/system/user';

import { nextTick, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import { message } from 'ant-design-vue';

import { assignUserRoleBatch } from '#/api/system/permission';
import { getUserPageNotRole } from '#/api/system/user';
import { TableAction } from '#/components/table-action';
import { $t } from '#/locales';
import { useGridAddColumns, useGridFormSchema } from '#/views/system/role/data';

const emit = defineEmits(['success']);
// 当前角色
const role = ref<SystemRoleApi.Role>();
// 创建 Modal
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    modalApi.lock();
    try {
      await assignUserRoleBatch({
        userIds: checkedIds.value,
        roleId: role.value.id,
      });
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },

  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const modalRole = modalApi.getData<SystemRoleApi.Role>();
    if (!modalRole) return;
    role.value = modalRole.role;
    await nextTick(); // 等待 Grid 挂载
    await gridApi.reload();
  },
});

// 表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'assign-user-form',
    columns: useGridAddColumns(),
    height: '600px',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!role.value?.id) return { list: [], total: 0 };
          return await getUserPageNotRole(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              roleId: role.value.id,
            },
            true,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<SystemUserApi.User>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemUserApi.User[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}
</script>

<template>
  <Modal title="未绑定该角色用户列表" class="w-2/3">
    <Grid table-title="">
      <template #toolbar-tools>
        <TableAction />
      </template>
    </Grid>
  </Modal>
</template>
